package com.douwong.student.popuwindow;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.douwong.student.R;
import com.douwong.student.contant.Config;
import com.douwong.student.utils.PreferencesUtils;


/**
 * 问答互动答案
 */
public class RightPopuwindow extends PopupWindow {
	private View view;
	private ImageView right;
	private AnimationDrawable animationDrawable;
	private MediaPlayer player;
	public RightPopuwindow(Context context, boolean isRight) {
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		view = inflater.inflate(R.layout.right_popu, null);
		right=(ImageView) view.findViewById(R.id.right);
		if(isRight){
			right.setBackgroundResource(R.drawable.right_anim);
			player= MediaPlayer.create(context, R.raw.reward_sound);
		}else {
			right.setBackgroundResource(R.drawable.error_anim);
			player= MediaPlayer.create(context, R.raw.error);
		}
		if (PreferencesUtils.getInstance().getBoolean(Config.IS_ROUND,true)){
			player.start();
			player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
				@Override
				public void onCompletion(MediaPlayer mp) {
					mp.release();
				}
			});
		}

/*		mp.setOnCompletionListener（新OnCompletionListener（）{        @覆盖
		公共无效onCompletion（MediaPlayer的MP）{
			mp.release（）;        }
		}）;*/

		animationDrawable = (AnimationDrawable) right.getBackground();
		animationDrawable.start();
		this.setContentView(view);
		this.setWidth(LayoutParams.MATCH_PARENT);
		this.setHeight(LayoutParams.MATCH_PARENT);
		// 设置SelectPicPopupWindow弹出窗体可点击
		this.setFocusable(true);
		ColorDrawable dw = new ColorDrawable(0x4c000000);
		this.setBackgroundDrawable(dw);

		view.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dismiss();

			}
		});

	}
	@Override
	public void dismiss() {
		super.dismiss();

		try {
			if(animationDrawable!=null){
				animationDrawable.stop();
				for (int i = 0; i < animationDrawable.getNumberOfFrames(); i++) {
					Drawable frame = animationDrawable.getFrame(i);
					if (frame instanceof BitmapDrawable) {
						((BitmapDrawable) frame).getBitmap().recycle();
					}
					frame.setCallback(null);
				}
				animationDrawable.setCallback(null);
			}			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}
